<?php

include_once($mcrp . 'config/config.php');
include_once($mcrp . 'functions/contests.php');
include_once($mcrp . 'functions/cache.php');

class UserInfos
{
	var $name = 'anonymous';
	var $password = '';
	var $email = '';
	var $id = 0;
	var $isadmin = false;
	var $points = 0;
	var $contestcompleted = array();
	var $currentcontest = 0;
	var $valid = -1;
	var $rank = 0;
	var $lasttry = 0;
	var $nanowin = 0;
	var $nanodefeat = 0;
}

function make_seed()
{
	list($usec, $sec) = explode(' ', microtime());
	return (float) $sec + ((float) $usec * 100000);
}

function CreateUser(&$UserInfos)
{
	srand(make_seed());
	global $mcsql;
	global $db;
	global $pun_config;
	
	$validnumber = rand(10000, 30000);
	$result = $mcsql->Query('INSERT INTO users(pseudo, password, registerdate, email, admin, points, contestcompleted, valid, rank, lasttry) VALUES(\'' . $UserInfos->name . '\', \'' . $UserInfos->password . '\', NOW(), \'' . $UserInfos->email . '\', FALSE, 0, \'\', ' . $validnumber . ', ' . (0xFFFFFF) . ', 0)');
	if($result === false) return false;
	$UserInfos = GetUser($UserInfos->name);

//	UpdateUser($UserInfos);
	
	$username = $UserInfos->name;
	$intial_group_id = 4;
	$password_hash = $UserInfos->password;
	$email1 = $UserInfos->email;
	$email_setting = 1;
	$timezone = 1;
	$dst = 0;
	$language = 'French';
	$now = time();
	
	$db->query('INSERT INTO ' . $db->prefix . 'users (username, group_id, password, email, email_setting, timezone, dst, language, style, registered, registration_ip, last_visit) VALUES(\'' . $db->escape($username) . '\', ' . $intial_group_id . ', \'' . $password_hash . '\', \'' . $db->escape($email1) . '\', ' . $email_setting . ', ' . $timezone . ' , ' . $dst . ', \'' . $db->escape($language) . '\', \'' . $pun_config['o_default_style'] . '\', ' . $now . ', \'' . get_remote_address() . '\', ' . $now . ')');// or error(‘Unable to create user’, __FILE__, __LINE__, $db->error());
	
	if(SendValidation($UserInfos) === false) return false;
	return true;
}

function SendValidation($UserInfos)
{
	$mail = $UserInfos->email;
	$Titre = 'Inscription µContest';
	$Text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
	$Text .= '<html xmlns="http://www.w3.org/1999/xhtml">';
	$Text .= '<head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /></head><body>';
	$Text .= 'Vous êtes maintenant inscrit sur µContest. Pour finaliser votre inscription, veuillez cliquer sur le lien ci-dessous :<br />';
	$Text .= '<a href="' . MC_ROOT . 'register.php?id=' . $UserInfos->id . '&valid=' . $UserInfos->valid . '">Finaliser l\'inscription</a>';
	$Text .= '</body></html>';
	$Headers  = 'MIME-Version: 1.0' . "\r\n";
	$Headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
	$Headers .= 'From: register@microcontest.com' . "\r\n" .
				'Reply-To: register@microcontest.com' . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
	return mail($mail, $Titre, $Text, $Headers);
}

function DeleteUser($Username)
{
	global $mcsql;
	$mcsql->Query('DELETE FROM users WHERE pseudo=' . $Username);
	ResetCacheParent('userscount');
}

function DeleteUserById($Id)
{
	global $mcsql;
	$mcsql->Query('DELETE FROM users WHERE id=' . $Id);
	ResetCacheParent('userscount');
}

function ValidateUser($UserInfos)
{
	$UserInfos->valid = 0;
	$UserInfos->rank = GetUsersCount() + 1;
	UpdateUser($UserInfos);
	ResetCacheParent('userscount');
}

function UpdateUser($UserInfos)
{
	global $mcsql;
	return $mcsql->Query('UPDATE users SET pseudo=\'' . $UserInfos->name . '\', password=\'' . $UserInfos->password . '\', email=\'' . $UserInfos->email . '\', points=' . $UserInfos->points . ', contestcompleted=\'' . (empty($UserInfos->contestcompleted)?'0':$UserInfos->currentcontest . ' ' . implode(' ', $UserInfos->contestcompleted)) . '\', valid=' . $UserInfos->valid . ', rank=' . $UserInfos->rank . ' WHERE id=' . $UserInfos->id);
}

function UpdateUserNano($UserInfos)
{
	global $mcsql;
	return $mcsql->Query('UPDATE users SET nanowin=' . $UserInfos->nanowin . ', nanodefeat=' . $UserInfos->nanodefeat. ' WHERE id=' . $UserInfos->id);
}

function SetUserAdmin($Id)
{
	global $mcsql;
	return $mcsql->Query('UPDATE users SET admin=1 WHERE id=' . $Id);
}

function SetUserNoAdmin($Id)
{
	global $mcsql;
	return $mcsql->Query('UPDATE users SET admin=0 WHERE id=' . $Id);
}

function SetUserLastTry($Id, $lt)
{
	global $mcsql;
	return $mcsql->Query('UPDATE users SET lasttry=' . $lt . ' WHERE id=' . $Id);
}

function GetUser($Username)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM users WHERE pseudo=\'' . $Username . '\'');
	if($u = mysql_fetch_array($answer))
	{
		$ui = FillUserInfos($u);
		return $ui;
	}
	return false;
}

function GetUserById($Id)
{
	if($Id == 0) return new UserInfos;
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM users WHERE id=\'' . $Id . '\'');
	if($u = mysql_fetch_array($answer))
	{
		$ui = FillUserInfos($u); 
		return $ui;
	}
	return false;
}

function FillUserInfos($User)
{
	$ui = new UserInfos;
	$ui->name = $User['pseudo'];
	$ui->password = $User['password'];
	$ui->email = $User['email'];
	$ui->id = (int)$User['id'];
	$ui->isadmin = (int)$User['admin'];
	$ui->points = (int)$User['points'];
	$ui->contestcompleted = explode(' ', $User['contestcompleted']);
	$ui->currentcontest = array_shift($ui->contestcompleted);
	if($ui->contestcompleted[0] == "") unset($ui->contestcompleted[0]);
	$ui->valid = $User['valid'];
	$ui->rank = (int)$User['rank'];
	$ui->lasttry = (int)$User['lasttry'];
	$ui->nanowin = (int)$User['nanowin'];
	$ui->nanodefeat = (int)$User['nanodefeat'];
	return $ui;
}

function GetAllUsers($order = null)
{
	global $mcsql;
	$users = array();
	$answer = $mcsql->Query('SELECT * FROM users WHERE valid=0' . ($order == null?'':' ORDER BY ' . $order));
	while($u = mysql_fetch_array($answer))
	{
		$ui = FillUserInfos($u);
		$users[$u['id']] = $ui;
	}
	return $users;
}

function GetAllUsersByPoints($Start = -1, $Count = 5)
{
	global $mcsql;
	$users = array();
	$answer = $mcsql->Query('SELECT * FROM users WHERE valid=0 ORDER BY points DESC' . ($Start == -1?'':' LIMIT ' . $Start . ',' . $Count));
	while($u = mysql_fetch_array($answer))
	{
		$ui = FillUserInfos($u);
		$users[$u['id']] = $ui;
	}
	return $users;
}

function GetAllUsersByNanoPoints($Start = -1, $Count = 5)
{
	global $mcsql;
	$users = array();
	$answer = $mcsql->Query('SELECT * FROM users WHERE valid=0 ORDER BY nanowin/(nanowin+nanodefeat) DESC' . ($Start == -1?'':' LIMIT ' . $Start . ',' . $Count));
	while($u = mysql_fetch_array($answer))
	{
		$ui = FillUserInfos($u);
		$users[$u['id']] = $ui;
	}
	return $users;
}

function IsUsernameExisting($Username)
{
	if(GetUser($Username) === false) return false;
	return true;
}

function IsValidated($u, $id)
{
	if(in_array($id, $u->contestcompleted)) return true;
	return false;
}

function GetUsersCount()
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT COUNT(*) FROM users WHERE valid=0');
	$res = mysql_fetch_array($answer);
	return $res[0];
}

function GetActiveUsersCount()
{	
	global $mcsql;
	$answer = $mcsql->Query('SELECT COUNT(*) FROM users WHERE valid=0 AND points <> 0');
	$res = mysql_fetch_array($answer);
	return $res[0];
}

function UpdateUsersPoints($contest, $delta)
{
	global $user;
	$users = GetAllUsers();
	foreach($users as $u)
	{
		if(in_array($contest, $u->contestcompleted))
		{
			$u->points -= $delta;
			UpdateUser($u);
		}
	}
}

function SetUsersPoints($contest, $points)
{
	global $user;
	$users = GetAllUsers();
	foreach($users as $u)
	{
		if(in_array($contest, $u->contestcompleted))
		{
			$u->points = $points;
			UpdateUser($u);
		}
	}
}

function ResetUsersPoints()
{
	global $mcsql;
	$mcsql->Query('UPDATE users SET points=0');
}

function ComputeClassement()
{
	$users = GetAllUsersByPoints();
	$rank = 1;
	foreach($users as $u)
	{
		$u->rank = $rank;
		$rank++;
		UpdateUser($u);
	}
}

function ComputeSingleRank($points)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT COUNT(*) FROM users WHERE valid=0 AND points>' . $points);
	$res = mysql_fetch_array($answer);
	return $res[0] + 1;
}

function CheckCurrentContest()
{
	global $mcuser;
	if($mcuser->id == 0) return false;
	if($mcuser->currentcontest < count($mcuser->contestcompleted)) return true;
	return false;
}

function GetLastValidatedContests()
{
	global $mcuser;
	$lastvc = array();
	for($i = $mcuser->currentcontest + 1; $i <= count($mcuser->contestcompleted); $i++)
		$lastvc[] = GetContestById($mcuser->contestcompleted[$i - 1]);
	return $lastvc;
}

function UpdateCurrentContest()
{
	global $mcuser;
	$mcuser->currentcontest = count($mcuser->contestcompleted);
	UpdateUser($mcuser);
}

?>